package com.lhl.netty.client;

import com.lhl.netty.common.ExceptionUtil;
import com.lhl.netty.common.NetMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class NetClientHandler extends ChannelInboundHandlerAdapter {
    private final static Logger logger = LoggerFactory.getLogger(NetClientHandler.class);
    private NetClient netClient;

    public NetClientHandler(NetClient netClient) {
        this.netClient = netClient;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        netClient.routing((NetMessage)msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        try{
            logger.error(cause.getMessage());
        }catch(Exception e){
            logger.error(ExceptionUtil.getMessage(e));
        }
    }

    /**
     * 断线重连
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.debug("与服务器连接已断开");
        super.channelInactive(ctx);
        //重新连接服务器
        ctx.channel().eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                netClient.connect();
            }
        }, 2, TimeUnit.SECONDS);
        ctx.close();
    }

}
